const fs = require('fs');
const path = require('path');

/**
 * 递归构建文件树，只显示“职位表”下的文件
 * 如果文件夹名称是数字类型，则倒序排列
 */
function buildFileTree(dirPath, parentName = '', isUnderPositionTable = false) {
  const tree = [];
  const items = fs.readdirSync(dirPath, { withFileTypes: true });

  // 判断子项是否为数字类型的文件夹，用于倒序排序
  const sortedItems = items.slice().sort((a, b) => {
    if (a.isDirectory() && b.isDirectory()) {
      const aNum = parseInt(a.name);
      const bNum = parseInt(b.name);
      if (!isNaN(aNum) && !isNaN(bNum)) {
        return bNum - aNum; // 数字类型文件夹倒序
      }
    }
    return 0; // 保持原顺序
  });

  sortedItems.forEach(item => {
    const fullPath = path.join(dirPath, item.name);
    let nodeName = item.name;

    if (!item.isDirectory()) {
      nodeName = path.parse(item.name).name; // 文件去掉后缀名
    }

    // 判断是否进入“职位表”目录
    let underPositionTable = isUnderPositionTable;
    if (item.isDirectory() && item.name === '职位表') {
      underPositionTable = true;
    }

    if (item.isDirectory()) {
      const children = buildFileTree(fullPath, parentName ? `${parentName}-${nodeName}` : nodeName, underPositionTable);
      if (underPositionTable) {
        // 职位表目录本身不显示
        tree.push(...children);
      } else if (children.length > 0) {
        tree.push({
          label: nodeName,
          value: nodeName,
          children
        });
      }
    } else if (underPositionTable) {
      tree.push({
        label: nodeName,
        value: nodeName,
        isLeaf: true
      });
    }
  });

  return tree;
}

module.exports = {
  buildFileTree,
};
